package com.sys.service.impl;

import com.sys.entity.BizGrowthBox;
import com.sys.entity.BizGrowthBoxItem;
import com.sys.entity.BizTask;
import com.sys.exception.CustomException;
import com.sys.mapper.BizGrowthBoxItemMapper;
import com.sys.mapper.BizGrowthBoxMapper;
import com.sys.mapper.BizTaskMapper;
import com.sys.service.GrowthBoxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GrowthBoxServiceImpl implements GrowthBoxService {

    @Autowired
    private BizGrowthBoxMapper growthBoxMapper;

    @Autowired
    private BizGrowthBoxItemMapper growthBoxItemMapper;

    @Autowired
    private BizTaskMapper taskMapper;

    @Transactional
    @Override
    public void addTaskToGrowthBox(Long userId, Long taskId, String note) {
        // 获取或创建成长盒
        BizGrowthBox growthBox = growthBoxMapper.findByUserId(userId);
        if (growthBox == null) {
            growthBox = new BizGrowthBox();
            growthBox.setUserId(userId);
            growthBox.setTitle("我的成长盒");
            growthBox.setDescription("记录孩子已掌握的任务，见证成长的每一步");
            growthBox.setCreateTime(LocalDateTime.now());
            growthBox.setDelFlag(0);
            growthBoxMapper.save(growthBox);
        }

        // 检查任务是否已在成长盒中
        if (growthBoxItemMapper.existsByTaskId(growthBox.getId(), taskId)) {
            throw new CustomException("该任务已在成长盒中");
        }

        // 添加任务到成长盒
        BizGrowthBoxItem item = new BizGrowthBoxItem();
        item.setGrowthBoxId(growthBox.getId());
        item.setTaskId(taskId);
        item.setAddedBy(userId);
        item.setAddedAt(LocalDateTime.now());
        item.setNote(note);
        item.setCreateTime(LocalDateTime.now());
        item.setDelFlag(0);
        growthBoxItemMapper.save(item);
    }

    @Override
    public List<Map<String, Object>> getGrowthBoxTasks(Long userId) {
        // 获取成长盒
        BizGrowthBox growthBox = growthBoxMapper.findByUserId(userId);
        if (growthBox == null) {
            return new ArrayList<>();
        }

        // 获取成长盒中的所有项
        List<BizGrowthBoxItem> items = growthBoxItemMapper.findByGrowthBoxId(growthBox.getId());
        
        // 组装返回数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (BizGrowthBoxItem item : items) {
            BizTask task = taskMapper.selectById(item.getTaskId());
            if (task != null && task.getDelFlag() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", item.getId());
                map.put("taskId", task.getId());
                map.put("title", task.getTitle());
                map.put("description", task.getDescription());
                map.put("domain", task.getDomain());
                map.put("difficulty", task.getDifficulty());
                map.put("addedAt", item.getAddedAt());
                map.put("note", item.getNote());
                result.add(map);
            }
        }
        
        return result;
    }

    @Transactional
    @Override
    public void removeFromGrowthBox(Long userId, Long itemId) {
        // 验证该项是否属于该用户
        BizGrowthBoxItem item = growthBoxItemMapper.findById(itemId);
        if (item == null) {
            throw new CustomException("成长盒项不存在");
        }
        
        BizGrowthBox growthBox = growthBoxMapper.findByUserId(userId);
        if (growthBox == null || !item.getGrowthBoxId().equals(growthBox.getId())) {
            throw new CustomException("无权限操作该项");
        }
        
        // 删除（软删除）
        growthBoxItemMapper.deleteById(itemId);
    }

    @Override
    public boolean isTaskInGrowthBox(Long userId, Long taskId) {
        BizGrowthBox growthBox = growthBoxMapper.findByUserId(userId);
        if (growthBox == null) {
            return false;
        }
        return growthBoxItemMapper.existsByTaskId(growthBox.getId(), taskId);
    }
    
    @Override
    public List<Long> getGrowthBoxTaskIds(Long userId) {
        BizGrowthBox growthBox = growthBoxMapper.findByUserId(userId);
        if (growthBox == null) {
            return new ArrayList<>();
        }
        return growthBoxItemMapper.findTaskIdsByGrowthBoxId(growthBox.getId());
    }
}